<template>
  <div class="crud-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名称" class="el-formitem">
          <el-input v-model="searchForm.name" placeholder="请输入用户名称" clearable />
        </el-form-item>
        <el-form-item label="手机号" class="el-formitem">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="用户账号" class="el-formitem">
          <el-input v-model="searchForm.userAcc" placeholder="请输入用户账号" clearable />
        </el-form-item>
        <el-form-item label="用户性别" class="el-formitem">
          <el-select v-model="searchForm.gender" placeholder="请选择用户性别" clearable>
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号码" class="el-formitem">
          <el-input v-model="searchForm.idCard" placeholder="请输入身份证号码" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.userStatus" placeholder="请选择状态" clearable>
            <el-option label="正常" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon>
              <Refresh />
            </el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <!-- <el-button type="primary" @click="handleAdd">
        <el-icon>
          <Plus />
        </el-icon>新增
      </el-button> -->
      <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
        <el-icon>
          <Delete />
        </el-icon>批量删除
      </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table v-loading="loading" :data="tableData" border style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="userId" label="编号" width="80" />
        <el-table-column prop="name" label="用户名称" />
        <el-table-column prop="phone" label="手机号" width="112" />
        <el-table-column prop="userAcc" label="用户账号" width="112" />
        <el-table-column prop="gender" label="用户性别" width="85" />
        <el-table-column label="用户头像" width="100">
          <template #default="{ row }">
            <img :src="row.avatar" alt="头像" style="width: 40px; height: 40px; border-radius: 50%; object-fit: cover" />
          </template>
        </el-table-column>
        <el-table-column prop="idCard" label="身份证号码" />
        <el-table-column prop="createTime" label="注册时间" />
        <el-table-column prop="balance" label="账户余额" />
        <el-table-column prop="userStatus" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.userStatus === 0 ? 'success' : 'danger'">
              {{ row.userStatus === 0 ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              <el-icon>
                <Edit />
              </el-icon>编辑
            </el-button>
            <el-button type="danger" link @click="handleDigDelete(row)">
              <el-icon>
                <Delete />
              </el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
        :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 新增表单 -->
    <el-dialog v-model="showAddDialog" title="新增用户" width="500px" :destroy-on-close="true">
      <el-form label-width="100px" :model="addForm" ref="formRef" :rules="rules">
        <el-form-item label="用户名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入用户名称" clearable />
        </el-form-item>
        <el-form-item label="手机号" prop="path">
          <el-input v-model="addForm.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="用户账号" prop="name">
          <el-input v-model="addForm.userAcc" placeholder="请输入用户账号" clearable />
        </el-form-item>
        <el-form-item label="用户性别" class="el-formitem">
          <el-select v-model="addForm.gender" placeholder="请选择用户性别" clearable>
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号码" prop="name">
          <el-input v-model="addForm.idCard" placeholder="请输入身份证号码" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="submitAddForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑表单 -->
    <el-dialog v-model="showUpDialog" title="修改用户" width="500px" :destroy-on-close="true">
      <el-form label-width="100px" :model="upForm" ref="formRef" :rules="rules">
        <el-form-item label="用户名称" prop="name">
          <el-input v-model="upForm.name" placeholder="请输入用户名称" clearable />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="upForm.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="用户账号" prop="userAcc">
          <el-input v-model="upForm.userAcc" placeholder="请输入用户账号" clearable />
        </el-form-item>
        <el-form-item label="用户性别" class="el-formitem" prop="gender">
          <el-select v-model="upForm.gender" placeholder="请选择用户性别" clearable>
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号码" prop="idCard">
          <el-input v-model="upForm.idCard" placeholder="请输入身份证号码" clearable />
        </el-form-item>
        <el-form-item label="账户余额" prop="balance">
          <el-input v-model="upForm.balance" placeholder="请输入账户余额" clearable />
        </el-form-item>
        <el-form-item label="用户头像" prop="avatar">
          <el-upload class="avatar-uploader" :show-file-list="false"
            :http-request="customRequest" :before-upload="beforeAvatarUpload">
            <img v-if="upForm.avatar" :src="upForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="userStatus">
          <el-select v-model="upForm.userStatus" placeholder="请选择状态">
            <el-option label="正常" :value="0" />
            <el-option label="停用" :value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showUpDialog = false">取消</el-button>
        <el-button type="primary" @click="submitUpForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog v-model="dialogVisible" title="确认删除" width="30%" :before-close="handleClose">
      <span>你确定要删除这条数据吗？此操作不可恢复。</span>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleDelete">确认</el-button>
      </template>
    </el-dialog>

    <!-- 批量删除确认弹窗 -->
    <el-dialog v-model="dialogVisible1" title="确认删除" width="30%" :before-close="handleClose">
      <span>你确定要删除这些数据吗？此操作不可恢复。</span>
      <template #footer>
        <el-button @click="dialogVisible1 = false">取消</el-button>
        <el-button type="primary" @click="handleDelete1">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { Fold, Expand, ArrowDown, Search, Refresh, Plus, Delete, Edit, View } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, messageConfig } from 'element-plus'
import request from '@/utils/request'
import dayjs from 'dayjs'

const router = useRouter()
const isCollapse = ref(false)
const menuList = ref([])
const activeMenu = ref('')
const showAddDialog = ref(false)
const showUpDialog = ref(false)
const roleOptions = ref([])
const formRef = ref(null)
// 控制弹窗显示
const dialogVisible = ref(false)
const dialogVisible1 = ref(false)

const addForm = ref({
  name: '',
  phone: '',
  userAcc: '',
  gender: '',
  idCard: ''
})

const upForm = ref({
  name: '',
  phone: '',
  userAcc: '',
  gender: '',
  idCard: '',
  balance: '',
  userStatus: '',
  avatar: '',
})

const rules = {
  name: [
    { required: true, message: '请输入用户名称', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5]+$/, message: '用户名称必须为中文', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  userAcc: [
    { required: true, message: '请输入用户账号', trigger: 'blur' },
    { pattern: /^[a-zA-Z][a-zA-Z0-9]{5,9}$/, message: '账号需以字母开头，6-10位字母或数字组合', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{17}[\dXx]$)/, message: '请输入正确的身份证号码格式', trigger: 'blur' }
  ],
  balance: [
    { required: true, message: '请输入账户余额', trigger: 'blur' },
    {
      pattern: /^(0|[1-9]\d*)(\.\d{1,2})?$/,
      message: '请输入正确的金额格式，如 100 或 100.00',
      trigger: 'blur'
    }
  ],
  avatar: [
    { required: true, message: '请上传用户头像', trigger: 'change' }
  ],
  userStatus: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 页面加载时获取菜单
onMounted(() => {
  //获取菜单列表
  getMenuList()
  //管理员列表
  adminList()
  //角色选项列表
  fetchRoles()
})

// 上传前验证
const beforeAvatarUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) ElMessage.error('上传头像图片只能是 JPG/PNG 格式')
  if (!isLt2M) ElMessage.error('上传头像大小不能超过 2MB')

  return isImage && isLt2M
}
//上传图片
const customRequest = async ({ file }) => {
  const formData = new FormData()
  formData.append('file', file)
  request.post(`/upload`,formData)
    .then(res => {
      console.log(res.data.url);
      upForm.value.avatar = res.data.url
      ElMessage.success("上传成功！")
    }).catch(err => {
      console.log(err);
    })
}

// 动态获取图标组件
const getIconComponent = (iconName) => {
  return ElementPlusIconsVue[iconName] || ElementPlusIconsVue['Menu']
}

// 获取菜单数据
const getMenuList = async () => {
  try {
    const userStr = sessionStorage.getItem('user')
    // if (!userStr) {
    //     ElMessage.error('用户未登录')
    //     router.push('/login')
    //     return
    // }

    const user = JSON.parse(userStr)
    const username = user.username


    request.get(`/menu/list?username=${encodeURIComponent(username)}`)
      .then(res => {
        // console.log(res);
        menuList.value = res.data.menu
        activeMenu.value = menuList.value[0].path
      }).catch(err => {
        console.log(err);

      })
  } catch (error) {
    ElMessage.error(error.message || '获取菜单失败')
    console.error('获取菜单失败:', error)
  }
}

// 点击菜单跳转
const handleMenuClick = (item) => {
  if (item.path) {
    router.push(item.path)
    activeMenu.value = item.path
  }
}

// 折叠菜单
const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
}

// 搜索表单数据
const searchForm = ref({
  name: '',
  phone: '',
  userAcc: '',
  gender: '',
  idCard: '',
  userStatus: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索
const handleSearch = () => {
  // console.log(searchForm.value);

  request.get('/user/searchuserlist', searchForm.value)
    .then((res) => {
      // console.log(res);
      if (res.code != 200) {
        return ElMessage.error(res.message)
      }
      ElMessage.success("搜索成功！")
      tableData.value = res.data.list;
      total.value = res.data.count;
    }).catch((err) => {
      console.log(err);
    })
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    name: '',
    phone: '',
    userAcc: '',
    gender: '',
    idCard: '',
    userStatus: ''
  }
  ElMessage.success("重置成功！")
  adminList()
}

// 表格选择
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 打开新增弹窗前重置表单
const handleAdd = () => {
  addForm.value = {
    name: '',
    phone: '',
    userAcc: '',
    gender: '',
    idCard: ''
  }
  showAddDialog.value = true
}

// 提交新增
const submitAddForm = () => {
  // const roleId = roleOptions.value[0].roleId
  // addForm.value.roleId = roleId;
  // console.log(addForm.value);

  formRef.value.validate((valid) => {
    if (valid) {
      request.post('/menumanager/add', addForm.value)
        .then((res) => {
          // console.log(res.message);
          ElMessage.success(res.message)
          addForm.value = {
            name: '',
            phone: '',
            userAcc: '',
            gender: '',
            idCard: ''
          }
          showAddDialog.value = false
          adminList()
        }).catch((err) => {
          console.log(err);
        })
    } else {
      ElMessage.error('请填写完整信息！')
    }
  })
}

// 编辑
const handleEdit = (row) => {
  showUpDialog.value = true;
  // console.log(row);
  upForm.value = structuredClone(row)
  // console.log(upForm.value);
}

// 提交编辑
const submitUpForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      request.put('/user/update', upForm.value)
        .then((res) => {
          // console.log(res);
          if(res.code != 200){
            ElMessage.error(res.message);
          }
          ElMessage.success(res.message);
          showUpDialog.value = false;
          adminList()
        }).catch((err) => {
          console.log(err);
        })
    } else {
      ElMessage.error('请填写完整信息！')
    }
  })
}

//关闭前处理
const handleClose = (done) => {
  done() // 关闭弹窗
}

const deleteForm = ref()
// 打开删除弹窗
const handleDigDelete = (row) => {
  dialogVisible.value = true
  deleteForm.value = structuredClone(row)
  // console.log(deleteForm.value);
}

// 确认删除处理函数
const handleDelete = () => {
  dialogVisible.value = false
  // console.log(adminState.value);

  request.delete('/user/delete', deleteForm.value)
    .then((res) => {
      // console.log(res);
      if (res.code != 200) {
        ElMessage.error(res.message)
      }
      ElMessage.success(res.message)
      adminList()
    }).catch((err) => {
      console.log(err);
    })
}

// 批量删除
const handleBatchDelete = () => {
  dialogVisible1.value = true
  // console.log(selectedRows.value);
}

// 确认批量删除处理函数
const handleDelete1 = () => {
  dialogVisible1.value = false
  
  const ids = selectedRows.value.map(item => item.userId);
  const state = selectedRows.value.map(item => item.userStatus);
  // console.log(ids,state,1454615);


  request.delete(`/user/delete1?userStatus=${state}&userId=${ids}`)
    .then((res) => {
      // console.log(res);
      if (res.code != 200) {
        ElMessage.error(res.message)
      }
      adminList()
      ElMessage.success(res.message)
    }).catch((err) => {
      console.log(err);
    })
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  adminList()
}

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  adminList()
}

//获取用户列表
const adminList = () => {
  request.get('/user/page', {
    page: currentPage.value,
    size: pageSize.value
  })
    .then((res) => {
      // console.log(res);
      if (res.code != 200) {
        ElMessage.error(res.message)
      }
      total.value = res.data.count;
      tableData.value = res.data.list;

    }).catch((err) => {
      console.error('获取失败：', err)
    })
}

// 获取菜单选项列表
const fetchRoles = () => {
  request.get('/menumanager/getmenu')
    .then((res) => {
      // console.log(res);
      roleOptions.value = res.data.list;
      // console.log(roleOptions.value[0].roleId);

    }).catch((err) => {
      console.log(err);

    })
}

</script>

<style>
.crud-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-area {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.operation-area {
  margin-bottom: 20px;
}

.table-area {
  margin-bottom: 20px;
}

.pagination-area {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.pagination-area span {
  padding-left: 10px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.el-button [class*="el-icon"]+span {
  margin-left: 5px;
}

.search-form .el-form-item {
  min-width: 190px;
}

.el-form-item span {
  /* padding-left: 10px; */
}

.el-formitem {
  width: 225px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}
</style>